package com.rxy.rpc.handler;

import com.alibaba.fastjson.JSON;
import com.rxy.rpc.common.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Callable;

/**
 * 客户端处理类
 * 1.发送消息
 * 2.接收消息
 */
public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable {

    private ChannelHandlerContext ctx;
    // 发送的消息
    private String requestMsg;
    private String responseMsg;

    public void setRequestMsg(String requestMsg) {
        this.requestMsg = requestMsg;
    }

    /**
     * 通道连接就绪事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.ctx = ctx;
    }

    /**
     * 通道读取就绪事件
     */
    @Override
    protected synchronized void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        responseMsg = msg;
        // 唤醒等待的线程
        notify();
    }

    /**
     * 发送消息到服务端
     * 调用wait()必须添加synchronized
     */
    @Override
    public synchronized Object call() throws Exception {
        ctx.writeAndFlush(requestMsg);
        wait();
        return responseMsg;
    }
}
